import { useContext, useEffect, useRef } from "react";
import { echaresContext } from "../../context/index";
import ApiClient from "../../axios/index";
import "./index.less";
import { EChartsType } from "echarts";
const Map = () => {
  const context = useContext(echaresContext);
  const trendRef = useRef<HTMLDivElement>(null);
  const allData = useRef(null);
  const echarts = useRef<EChartsType | null>(null);
  // 初始化
  const initEcharts = () => {
    echarts.current = context.init(trendRef.current, "dark");
    const option = {
      title: {
        text: "",
        left: "center",
      },
      tooltip: {},
      legend: {
        orient: "vertical",
        left: "left",
        bottom: "5%",
        textStyle: {
          color: "#fff",
          fontSize: 12,
        },
      },
      series: [
        {
          type: "pie",
          label: {
            show: false,
          },
          emphasis: {
            label: {
              show: true,
              formatter: (arg) => {
                const total = arg.data.children.reduce((pre, item) => {
                  return pre + item.value;
                }, 0);
                return `${arg.data.name} \n${arg.data.value} ${(
                  (arg.data.value / total) *
                  100
                ).toFixed(2)}%`;
              },
            },
          },
        },
      ],
    };
    echarts.current && echarts.current.setOption(option);
  };
  // 更新数据
  const updateEcharts = () => {
    const seriesArr =
      allData.current &&
      allData.current[0].children.map((item) => {
        return {
          name: item.name,
          value: item.value,
        };
      });
    const option = {
      series: [
        {
          data: allData.current[0].children!,
        },
      ],
      // legend: {
      //   data: seriesArr!.map((item) => item.name),
      // },
    };
    // 更新数据
    echarts.current && echarts.current.setOption(option);
  };
  // 屏幕大小改变
  const screenResize = () => {
    const fontSize = (trendRef.current?.offsetWidth / 100) * 3.6;
    const option = {
      legend: {
        itemWidth: fontSize,
        itemHeight: fontSize,
        itemGap: fontSize,
        textStyle: {
          fontSize: fontSize / 2,
        },
      },
    };
    echarts.current && echarts.current.setOption(option);
  };
  // 获取数据
  const getData = () => {
    const apiClient = new ApiClient();
    apiClient.get("/hot").then((res) => {
      allData.current = res.data;
      updateEcharts();
    });
    // 获取数据
  };
  useEffect(() => {
    initEcharts();
    getData();
    window.addEventListener("resize", screenResize);
    screenResize();
    return () => {
      window.removeEventListener("resize", screenResize);
    };
  }, []);
  return <div className="trend-container" ref={trendRef}></div>;
};
export default Map;
